<?php
class Tedi_NOHUP
{
    public static function execute($scriptFile, $parameters = '', $priority = 0)
    {
        if(self::isWindows())
        {
            $phpFile  = str_replace('/', '\\', $scriptFile);
            $WshShell = new COM("WScript.Shell");
            $process  = $WshShell->Exec("php \"$scriptFile\" $parameters");
            return $process->ProcessID;
        }
        else
        {
            if($priority)
            {
                return shell_exec("nohup nice -n $priority php \"$scriptFile\" $parameters > /dev/null 2>&1 & echo $!");
            }
            else
            {
                return shell_exec("nohup php \"$scriptFile\" $parameters > /dev/null 2>&1 & echo $!");
            }
        }
    }

    public static function isRunning($PID)
    {       
        if(self::isWindows())
        {
            exec("tasklist /fi \"PID eq $PID\"", $ProcessState);

            $ProcessState = implode("\n", $ProcessState);

            if(strpos($ProcessState, "$PID") !== false)
            {
                if( (strpos($ProcessState, 'php-cgi.exe') !== false) || (strpos($ProcessState, 'php.exe') !== false) )
                {
                    return true;
                }
            }
			
            return false;
        }
        else
        {
            exec("ps $PID", $ProcessState);
            return (count($ProcessState) >= 2);
        }
    }


    public static function kill($PID)
    {
        if(!$PID)
        {
            return false;
        }
        
        if(self::isRunning($PID))
        {
            if(self::isWindows())
            {
                exec("taskkill /F /PID $PID");
                return true;
            }
            else
            {
                exec("kill -KILL $PID");
                return true;
            }
        }

        return false;
    }


    protected static function isWindows()
    {
        return (strpos(PHP_OS, 'WIN') !== false);
    }
}
?>
